<?php

// SWFAddress code fully compatible with Apache HTTPD

class SWFAddress
{
	//--------------------------------------------------------------------------
	//
	//  Instance properties
	//
	//--------------------------------------------------------------------------
	public $base;
	public $swfaddress = '';
	
	//--------------------------------------------------------------------------
	//
	//  API
	//
	//--------------------------------------------------------------------------
	/**
	 * Initialize swfaddress optimizer manager.
	 */
	public function init()
	{
		$this->base = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], '/'));

		if ('application/x-swfaddress' == (isset($_SERVER['CONTENT_TYPE']) ? $_SERVER['CONTENT_TYPE'] : 
		    (isset($_SERVER['HTTP_CONTENT_TYPE']) ? $_SERVER['HTTP_CONTENT_TYPE'] : ''))) {
		    $_SESSION['swfaddress'] = $_SERVER['QUERY_STRING'];
		    echo('location.replace("' . $this->base . '#' . $_SERVER['QUERY_STRING'] . '")');
		    exit();
		}

		if (isset($_SESSION['swfaddress'])) {
		    $this->swfaddress = $_SESSION['swfaddress'];
		    unset($_SESSION['swfaddress']);
		} else {
		    $page = substr($_SERVER['PHP_SELF'], strrpos($_SERVER['PHP_SELF'], '/') + 1);
		    $this->swfaddress = str_replace($this->base, '', (strpos($page, '.php') && $page != 'index.php') ? $_SERVER['REQUEST_URI'] : str_replace($page, '', $_SERVER['REQUEST_URI']));
		}

		$this->swfaddress = preg_replace('/^([^\?.]*[^\/])(\?|$)/', '$1/$2', $this->swfaddress, 1);
		
		$query_string = (strpos($this->swfaddress, '?')) ? substr($this->swfaddress, strpos($this->swfaddress, '?') + 1, strlen($this->swfaddress)) : '';
		$swfaddress_path = ($query_string != '') ? substr($this->swfaddress, 0, strpos($this->swfaddress, '?')) : $this->swfaddress;
		$swfaddress_parameters = array();
		
		if (strpos($this->swfaddress, '?')) {
		    $params = explode('&', str_replace($swfaddress_path . '?', '', $this->swfaddress));
		    for ($i = 0; $i < count($params); $i++) {
		        $pair = explode('=', $params[$i]);
		        $swfaddress_parameters[$pair[0]] = $pair[1];
		    }
		}
	}
	
	/**
	 * Return swfaddress chunks.
	 */
	public function getChunks()
	{
		$chunks = array();
		foreach(explode("/", $this->swfaddress) as $value) {
			if ($value != "") {
				$chunks[] = $value;
			}
		}
	 	return $chunks;
	}
	 
	/**
	 * Build and return swfaddress optimizer URL.
	 */
	public function writeOptimizer($resource)
	{
		echo($this->base . $resource . (strstr($resource, '?') ? '&amp;' : '?') . 'swfaddress=' . urlencode($this->swfaddress) . '&amp;base=' . urlencode($this->base));        
	}
}

?>